package com.hup.restTimer.service;

import com.hup.restTimer.model.AppConfig;
import com.hup.restTimer.view.main.MainWindow;
import com.hup.utils.commons.exception.AppExceptionHandler;
import com.hup.utils.commons.io.FileUtil;
import com.hup.utils.swing.IconUtil;
import com.hup.utils.swing.ImageUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Collections;
import java.util.Vector;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author hugan
 * @date 2022/10/2
 */
@Slf4j
@Component
public class ImageService {

    private static final String[] IMG_EXT = {
            ".png",
            ".jpg",
            ".jpeg",
            ".gif",
            ".bmp",
    };

    private final AppConfig config;
    private final ReentrantLock lock;
    private Vector<String> imageList;

    private long lastChangeTime;
    /**
     * 当前的图片index
     */
    private int curIndex;

    public ImageService(AppConfig config) {
        this.config = config;
        lock = new ReentrantLock();
        imageList = new Vector<>();
        onImagePathUpdated();
    }

    /**
     * 每秒功能
     */
    public void doTickTask(MainWindow mainWindow) {
        if (!config.imageShow || !config.isResting) {
            mainWindow.getBackgroundLabel().setBackgroundImage(null);
            return;
        }
        long diff = System.currentTimeMillis() - lastChangeTime;
        if (diff < config.imageChangeTime) return;
        doChangeImage(mainWindow);
    }

    public void doChangeImageIfShow(MainWindow mainWindow) {
        if (config.imageShow && config.isResting) {
            doChangeImage(mainWindow);
        }
    }

    public void doChangeImage(MainWindow mainWindow) {
        String imagePath = null;
        try {
            lock.lock();
            //log.info("更换图片.st");
            if (!imageList.isEmpty()) {
                curIndex++;
                if (curIndex > imageList.size() - 1){
                    curIndex = 0;
                    if (config.imageRandom) Collections.shuffle(imageList);
                    log.info("重新遍历");
                }
                /*
                此处,若文件被删除或修改,"通常"不会有问题,仍会显示已缓存的图像
                    因为jdk 会按照文件路径缓存图像
                    未深究 缓存回收时机
                要无缓存则使用: IconUtil.getFileImageNoCache
                 */
                imagePath = imageList.get(curIndex);
                Image image = IconUtil.getFileImage(imagePath, "背景图");
                BufferedImage bf = ImageUtil.updateAlpha(ImageUtil.getImage(image), config.imageAlpha);
                mainWindow.getBackgroundLabel().setBackgroundImage(bf);
            } else {
                mainWindow.getBackgroundLabel().setBackgroundImage(null);
            }
        } catch (Exception e) {
            AppExceptionHandler.handle("更换图片异常,", e);
        } finally {
            lastChangeTime = System.currentTimeMillis();//始终都更新时间
            log.info("更换图片.ed, {}", imagePath);
            lock.unlock();
        }
    }

    /**
     * 更新图片列表
     */
    public void onImagePathUpdated() {
        try {
            lock.lock();
            log.info("onImagePathUpdated.st");
            //
            imageList.clear();
            if (StringUtils.isBlank(config.imagePath)) return;
            File dir = new File(config.imagePath);
            if (!dir.isDirectory()) {
                log.warn("不是目录={}", config.imagePath);
                return;
            }

            File[] files = dir.listFiles();
            if (files == null) return;
            for (File file : files) {
                if (FileUtil.extOf(file, IMG_EXT)) imageList.add(file.getAbsolutePath());
            }

            if (config.imageRandom) Collections.shuffle(imageList);
            curIndex = -1;
            lastChangeTime = 0;
        } finally {
            log.info("onImagePathUpdated.ed={}", imageList.size());
            lock.unlock();
        }
    }

}
